﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;

namespace AnalizadorLéxico
{
    public class Buffer
    {
        string _bufferPrincipal = "";
        string _bufferSecundario = "";
        StreamReader _lectorBuffer;
        int _bufferALeer = 0;
        int _caracterActual = 0;
        int _tamañoBuffer = 4;

        public Buffer(string archivo)
        {
            _lectorBuffer = new StreamReader(new FileStream(archivo, FileMode.Open, FileAccess.Read));

            _bufferPrincipal = GetNextBuffer();
            _bufferSecundario = GetNextBuffer();
        }

        private string GetNextBuffer()
        {

            if (_lectorBuffer == null) return "";

            char[] buffer = new char[_tamañoBuffer];

            int retval = _lectorBuffer.ReadBlock(buffer, 0, _tamañoBuffer);

            if (_lectorBuffer.EndOfStream)
            {
                _lectorBuffer.Close();
                _lectorBuffer.Dispose();
                _lectorBuffer = null;
            }

            return new string(buffer);
        }

        public Nullable<char> SiguienteToken()
        {

            if (_caracterActual == _bufferPrincipal.Length)
            {
                _bufferPrincipal = _bufferSecundario;
                _caracterActual = 0;
                _bufferSecundario = GetNextBuffer();
            }

            return Convert.ToChar((_caracterActual < _bufferPrincipal.Length) ? _bufferPrincipal[_caracterActual++] : (Nullable<char>)null);
        }

        public Nullable<char> LookAhead()
        {
            return (_caracterActual < _bufferPrincipal.Length) ? _bufferPrincipal[_caracterActual] : ((_bufferSecundario.Length > 0) ? _bufferSecundario[0] : (Nullable<char>)null);
        }
    }
}
